package br.com.future.controllers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import br.com.future.dao.FutureDao;
import br.com.future.model.LoginRequest;

@Controller
@RequestMapping("/login")
public class LoginController {

	private static final Log LOG = LogFactory.getLog(LoginController.class);
	private FutureDao futureDao;

	@RequestMapping(method = RequestMethod.POST)
	public void showUserForm(HttpServletRequest request, HttpServletResponse response) throws IOException {

		if (LOG.isDebugEnabled())
			LOG.debug("Entering LoginController");

		// Get the JSON request from httpRequest
		String jsonRequest = parseResponseBody(request);

		String strResponse;

		// Check if we have any data on the request body
		if (StringUtils.isBlank(jsonRequest))
			strResponse = loginFail(response, "Missing login body");

		// Check if the body is a readable JSON request
		LoginRequest loginrequest = extractUsernamePasswd(jsonRequest);
		if (null == loginrequest)
			strResponse = loginFail(response, "Impossible to parse JSON request");
		else {
			/*
			 * On this point we have at least one username/password. So lets validate them on DB!
			 */
			if(futureDao.checkCredentials(loginrequest.getUsername(), loginrequest.getPassword()))
				strResponse = loginSuccess(response);
			else
				strResponse = loginFail(response, "Wrong credentials for user: " + loginrequest.getUsername());
		}	

		LOG.info("LoginController called - returning with: " + strResponse);
	}

	private String parseResponseBody(HttpServletRequest request) throws IOException {
		BufferedReader reader = request.getReader();
		StringBuilder sb = new StringBuilder();
		String line = reader.readLine();
		while (line != null) {
			sb.append(line + "\n");
			line = reader.readLine();
		}
		reader.close();
		String jsonRequest = sb.toString();
		return jsonRequest;
	}

	private LoginRequest extractUsernamePasswd(String jsonRequest) throws IOException, JsonParseException,
			JsonMappingException {
		try {
			ObjectMapper mapper = new ObjectMapper();
			LoginRequest loginRequest = mapper.readValue(jsonRequest, LoginRequest.class);
			System.out.println(loginRequest.getUsername());
			System.out.println(loginRequest.getPassword());
			return loginRequest;
		} catch (JsonParseException e) {
			LOG.error("Impossible to parse login json request", e);
			return null;
		}
	}

	private String loginFail(HttpServletResponse response, String errMessage) throws IOException {

		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		response.setContentType("application/json; charset=UTF-8");

		PrintWriter out = response.getWriter();
		StringBuffer sb = new StringBuffer();
		sb.append("{").append("\"status\":").append("\"");
		sb.append("fail").append("\",");
		sb.append("\"message\":\"").append(errMessage).append("\"}");
		out.println(sb.toString());
		return sb.toString();
	}

	private String loginSuccess(HttpServletResponse response) throws IOException {

		response.setStatus(HttpServletResponse.SC_OK);
		response.setContentType("application/json; charset=UTF-8");

		PrintWriter out = response.getWriter();
		StringBuffer sb = new StringBuffer();
		sb.append("{\"status:\":");
		sb.append("\"");
		sb.append("success");
		sb.append("\"}");
		out.println(sb.toString());
		return sb.toString();
	}

	public FutureDao getFutureDao() {
		return futureDao;
	}

	public void setFutureDao(FutureDao futureDao) {
		this.futureDao = futureDao;
	}
}
